
import Foundation

class OsnLogin {
    func setBaseUrl(_ url:String){
        ghttpService.setBaseUrl(url)
    }
    func isLogined()->Bool{
        return gimService.isLogined()
    }
    func saveLoginData(_ data:[String:Any]){
        UserDefaults.standard.set(OsnUtils.toString(data), forKey: "ospn_login_data")
        UserDefaults.standard.synchronize()
    }
    func loadLoginData()->[String:Any]{
        let data = UserDefaults.standard.string(forKey: "ospn_login_data")
        return OsnUtils.toJson(data) ?? [:]
    }
    func loginWithCode(_ user:String, _ code:String) async -> ([String:Any]?,OspnError?) {
        let (loginData, err) = await ghttpService.loginWithCode(user, code)
        if let err = err { return (nil, err) }
        //print("\(loginData)")
        saveLoginData(loginData!)
        if let err = await gimService.loginWithConfig(loginData!) {
            return (nil, err)
        }
        return (loginData, nil)
    }
    func loginWithGetWebUrl(_ scanStr:String) -> (String) {
        let dic = OsnUtils.toJson(scanStr)//json2Dics(scanStr) ?? [:]
        var mutableDic = dic
        let timestamp = OsnUtils.getTimeStamp()
        mutableDic?["timestamp"] = timestamp
        let calc = "\(dic?["url"] ?? "")\((dic!["webId"] ?? ""))\(timestamp)"
        let hash = EcUtils.osnHash(data: calc.data(using: .utf8)!)//.hashData(calc.data(using: .utf8)!)
        let sign = EcUtils.osnSign(priKey: gimService.mOsnKey, data: hash.data(using: .utf8)!)//.sign(hash!.data(using: .utf8)!)
        mutableDic!["sign"] = sign
        mutableDic!["osnId"] = gosnUser.myId()
        let url = dic?["url"] as! String
        return (url)
    }
    func loginWithPassword(_ user:String, _ pass:String) async -> ([String:Any]?,OspnError?) {
        let (loginData, err) = await ghttpService.loginWithPassword(user, pass)
        if let err = err { return (nil, err)}
        print("\(loginData)")
        saveLoginData(loginData!)
        if let err = await gimService.loginWithConfig(loginData!) {
            return (nil, err)
        }
        return (loginData, nil)
    }
    func register(_ user:String, _ pass:String, _ code:String) async -> ([String:Any]?,OspnError?) {
        return await ghttpService.register(user, pass, code)
    }
    func getCode(_ account:String,_ type:Int) async -> ([String:Any]?,OspnError?) {
        return await ghttpService.getCode(account, type)
    }
}
let gosnLogin = OsnLogin()
